package yl.hs.bmipfull.security;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import yl.hs.bmipfull.exception.TokenOutTimeException;
import yl.hs.bmipfull.utils.ResultCode;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.viewmodels.WebResult;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @author 华砂信息 <br/>
 * 身份验证过滤器
 */
public class AuthenticationFilter extends BasicAuthenticationFilter {

    public AuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 获取token, 并检查登录状态

        try {
            SecurityUtils.checkAuthentication(request);
            chain.doFilter(request, response);
        } catch (TokenOutTimeException ee) {
            var webResult = new WebResult(ResultCode.UnAuthentication, true, ee.getMessage());
            Tl.writeObjectToResponse(response, webResult);
        }
    }

    private boolean checkUrl(String requestURI) {
        var excludeString = Arrays.stream("/swagger-,/webjars/,/jmreport/,/v3/,favicon.ico,/largescale/*".split(",")).collect(Collectors.toList());
        AtomicBoolean flag = new AtomicBoolean(false);
        excludeString.forEach(t -> {
            if (requestURI.indexOf(t) >= 0) {
                flag.set(true);
            }
        });
        return flag.get();

    }

}
